package com.luomu.base.api.cookBook.excel.contant;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 时间格式化
 * @author yanhan
 * @date 2024-12-04
 */
public class TimestampDeserializer extends JsonDeserializer<Date> {

	private static final SimpleDateFormat DATE_SDF = new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat DATE_TIME_SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

		try {
			if(jsonParser.getCurrentToken().isNumeric()){
				return new Date(jsonParser.getLongValue());
			}
		}catch (Exception e){
			e.printStackTrace();
			throw new IOException("Unparseable date: \"" + jsonParser.getText() + "\"", e);
		}


		try {
			// 尝试使用 'yyyy-MM-dd' 格式解析
			return DATE_SDF.parse(jsonParser.getText());
		} catch (Exception e) {
			e.printStackTrace();
			try {
				// 尝试使用 'yyyy-MM-dd HH:mm:ss' 格式解析
				return DATE_TIME_SDF.parse(jsonParser.getText());
			} catch (ParseException ex) {
				ex.printStackTrace();
				throw new IOException("Unparseable date: \"" + jsonParser.getText() + "\"", ex);
			}
		}

	}
}
